package com.zhiwang.planet.ui.main

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import com.zhiwang.planet.R
import com.zhiwang.planet.event.LoginEvent
import com.zhiwang.planet.event.LogoutEvent
import com.zhiwang.planet.event.NetWorkConnectedEvent
import com.zhiwang.planet.ui.BaseFragment
import com.zhiwang.planet.ui.LoginActivity
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.ui.guessboard.RankActivity
import com.zhiwang.planet.ui.my.BindPayPasswordActivity
import com.zhiwang.planet.ui.my.BonusTransformActivity
import com.zhiwang.planet.ui.my.ModifyPasswordActivity
import com.zhiwang.planet.util.Store
import com.zhiwang.planet.util.Store.Store.URL_VIP_CENTER
import com.zhiwang.planet.util.quickStartActivity
import kotlinx.android.synthetic.main.fragment_vip.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class VipFragment : BaseFragment() {


    val TAG = "VipFragment"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        EventBus.getDefault().register(this)
    }

    override fun onDetach() {
        super.onDetach()
        EventBus.getDefault().unregister(this)
    }
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_vip, container, false)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initWebView()
        loadUrl()
        swipeRefreshLayout.setOnRefreshListener {
            loadUrl()
            swipeRefreshLayout.finishRefresh()
        }
        vip_master_webview.webView?.addJavascriptInterface(this, "android")
    }


    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {

        val settings = vip_master_webview.webView?.settings
        settings?.javaScriptEnabled = true
        settings?.useWideViewPort = true
        settings?.textZoom = 100
        vip_master_webview.setRetryListener(::loadUrl)
        vip_master_webview.webView?.webChromeClient = object : WebChromeClient() {

            override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
                return super.onJsAlert(view, url, message, result)
            }

            override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
                return super.onConsoleMessage(consoleMessage)
            }
        }
        vip_master_webview.webView
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetWorkConnected(e: NetWorkConnectedEvent) {
        loadUrl()
    }

    fun loadUrl() {
        vip_master_webview.webView?.loadUrl(URL_VIP_CENTER, webViewHeader())
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLogin(e: LoginEvent) {
        loadUrl()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLogout(e: LogoutEvent) {
        loadUrl()
    }

    /**
     * 去往 vip 会员中心
     */
    @JavascriptInterface
    fun openMemberShip() {
        WebViewActivity.loadImmersive(requireContext(), Store.URL_MEMBER_SHIP)
    }

    @JavascriptInterface
    //福利卡
    fun goWelfareCards() {
        quickStartActivity(BonusTransformActivity::class.java)
    }

    @JavascriptInterface
    // 忘记密码
    fun  goForgotPassword(){
        quickStartActivity(ModifyPasswordActivity::class.java)
    }

    /**
     * 打开链接
     * [url] 链接
     * [isExternal]  true 用外部浏览器打开 ;false 在 app内加载该链接
     */
    @JavascriptInterface
    fun openLink(url: String, isExternal: String) {
        when (isExternal) {
            "false" -> WebViewActivity.load(context!!, url)
            "true" -> {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                context!!.startActivity(intent)
            }
        }
    }

    @JavascriptInterface
    fun requestLogin() {
        onAuthExpired()
    }

    /**
     * 竞猜榜单
     */
    @JavascriptInterface
    fun goRank() = quickStartActivity(RankActivity::class.java)

    @JavascriptInterface
    // 忘记密码
    fun goForgotPayPassword() {
        quickStartActivity(BindPayPasswordActivity::class.java)
    }

    @JavascriptInterface
    fun setRefreshEnabled(enable: String) {
        swipeRefreshLayout.setEnableRefresh(enable.toBoolean())
    }
}